import asyncio, asyncpg
import traceback


async def main():
    connection = await asyncpg.connect(
        host="127.0.0.1",
        port="5432",
        database="products",
        user="around",
        password="zhouwei",
    )
    # 创建事务实例
    transaction = connection.transaction()
    # 开始事务
    await transaction.start()
    try:
        await connection.execute("insert into brand values (107, 'brand_1')")
    except asyncpg.PostgresError:
        print("出现错误，回滚事务")
        await transaction.rollback()
    else:
        print("没有错误，事务提交")
        await transaction.commit()

    query = """
                select * from brand where brand_name like 'brand%'
            """
    brands = await connection.fetch(query)
    print(brands)

    await connection.close()

asyncio.run(main())
